import GameData_blxf from "../GameData/GameData";
import BaseShopData_blxf from "../GameData/ShopData";
import { BaseVendorData_blxf } from "../GameData/VendorData";
import { EnumManager_blxf } from "../Manager/EnumManager";
import PageManager_blxf from "../Manager/PageManager";
import AudioModule_blxf from "../Module/AudioModule";
import { ConfigModule_blxf } from "../Module/ConfigModule";
import { LoadModule_blxf } from "../Module/LoadModule";
import NodePool_blxf from "../Module/NodePool";
import { NumModule_blxf } from "../Module/NumModule";
import PublicModule_blxf from "../Module/PublicModule";
import { UtilsModule_blxf } from "../Module/UtilsModule";
import ShopItem_blxf from "./shopItem";


const {ccclass, property} = cc._decorator;

/** 摊位item */
@ccclass
export default class VendorItem_blxf extends cc.Component {

    @property({ type: cc.Node, tooltip: '盒子' })
    nodeBox: cc.Node = null;

    @property({ type: cc.Prefab, tooltip: '商品item' })
    shopItem : cc.Prefab = null;

    @property({ type: cc.Prefab, tooltip: '商品item背景' })
    shopItemBg : cc.Prefab = null;

    @property({ type: cc.Sprite, tooltip: '摊位图片' })
    vendorImg : cc.Sprite = null;

    @property({ type: cc.Node, tooltip: '商品item背景盒子' })
    shopItemBgBox : cc.Node = null;

    @property({ type: cc.Node, tooltip: '商品盒子' })
    shopBox : cc.Node = null; 

    @property({ type: cc.Node, tooltip: '摊位锁' })
    unlockBox : cc.Node = null;

    @property({ type: cc.Sprite, tooltip: '解锁图标' })
    unlockIcon : cc.Sprite = null;

    @property({ type: cc.Node, tooltip: 'icon盒子' })
    unlockIconBox: cc.Node = null;

    @property({ type: cc.Label, tooltip: '解锁文字' })
    unlockText : cc.Label = null;

    @property({ type: cc.Node, tooltip: '锁图标' })
    lockIconNode : cc.Node = null;

    @property({ type: cc.Node, tooltip: '集满特效' })
    effectNode : cc.Node = null;

    @property({ type: cc.Node, tooltip: '摊位等级' })
    vendorLvText: cc.Node = null;

    @property({ type: cc.Node, tooltip: '摊位升级盒子' })
    vendorLvUpBox: cc.Node = null;

    @property({ type: cc.Node, tooltip: '升级动画盒子' })
    lvUpSpineBox: cc.Node = null;

    @property({ type: cc.Node, tooltip: '等级数' })
    spineLvText: cc.Node = null;

    @property({ type: cc.Node, tooltip: '集满动画盒子' })
    allSpineBox: cc.Node = null;


    @property({ tooltip: '传入参数' })
    _data : BaseVendorData_blxf = null;

    @property({ tooltip: '运行帧数' })
    _dtNum : number = 0;

    @property({ tooltip: '可摆放商品总数' })
    _totalNum : number = 0;

    @property({ tooltip: '更新商品倒计时' })
    _updateTimer: number = 0;

    @property({ tooltip: '是否已加载锁动画' })
    _isLoadAnimation: boolean = false;

    @property({ tooltip: '锁动画' })
    _unlockAnimation: cc.Node = null;

    @property({ tooltip: '集满动画' })
    _allAnimation: cc.Node = null;

    @property({ tooltip: '是否已加载集满动画' })
    _isLoadAllAnimation: boolean = false;

    @property({ tooltip: '是否有摊位等级动画' })
    _isLvTween: boolean = false;

    @property({ tooltip: '分享id' })
    _shareId: number = null;

    @property({ tooltip: '是否分享解锁' })
    _isShare: boolean = false;

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start () {

    }

    /**
     * 初始化数据
     * @param data 传入参数
     */
    initData_blxf ( data: BaseVendorData_blxf ) {
        // cc.log('data >>', data.vendorId, data);
        this._data = data;

        let { maxNum, baseNum } = this._data;
        this._totalNum = baseNum * maxNum;

        // this.loadShopBgItem( 0 );

        this.updateUI_blxf();
        this.updateVendorLv_blxf( true );

        this.initEvent_blxf();
    }

    /** 初始化监听事件 */
    initEvent_blxf () {
        let { vendorId } = this._data;

        cc.game.on(`updateVendorLv_blxf_${vendorId}`, this.updateVendorLv_blxf, this);
    }

    update ( dt: number ) {
        this._dtNum += 1;

        if ( this._updateTimer > 0 ) {
            this._updateTimer -= dt;
        }

        this._updateTimer <= 0 && this.loadShopList_blxf();


        // 标记检测
        let _isUpdateMark: boolean = this._dtNum % 10 == this._data.vendorId
        _isUpdateMark && this.onCheckIsMark_blxf();

        this._dtNum % 6 == 1 && this.onCheckIsUnlock_blxf();
        this._dtNum % 7 == 1 && this.onCheckIsAllShop_blxf();

        if ( this._dtNum % 8 == 1 ) {
            this.shopBox.scale = PublicModule_blxf.isVendorLvUp ? 0 : 1;

            this.onVendorLvTween_blxf();
        }
    }

    /** 更新节点显示 */
    updateNode_blxf ( isShow: boolean ) {
        this.nodeBox.opacity = isShow ? 255 : 0;
    }

    onCheckIsAllShop_blxf () {
        let _isAllShop: boolean = this._data.onCheckIsAllShop_blxf();
        this.updateEffect_blxf( _isAllShop );
    }

    /** 更新集满效果 */
    updateEffect_blxf ( isShow: boolean ) {
        this.effectNode.opacity = isShow ? 255 : 0;

         isShow && this.loadVendorAllSpine_blxf();
        !isShow && this.onClearAllAnimation_blxf();
    }

    /** 更新摊位UI */
    updateUI_blxf () {
        let { isUnlock, unlockType, unlockNum } = this._data;

        this.updateNode_blxf( true );

        let _isVideo: boolean = unlockType == 9;

        // 更新分享相关数据
        !isUnlock && _isVideo && this.onUpdateShareData_blxf();
        if ( this._isShare ) unlockType = EnumManager_blxf.gameNumType.NUM_SHARE_BG;

        this.unlockIcon.node.x = this._isShare ? 12 : 0;
        this.unlockText.node.x = (_isVideo || this._isShare) ? 20 : 14;
        let _msg: string = _isVideo ? `${unlockNum}` : `第${unlockNum}关`;
        UtilsModule_blxf.instance.setText_blxf( this.unlockText.node, _msg );

        this.unlockBox.active = !isUnlock;

        !isUnlock && UtilsModule_blxf.instance.loadIconImg_blxf( unlockType, this.unlockIcon, this.unlockIconBox );

        // // 已解锁，加载商品背景
        // isUnlock && this.loadShopBgItem( 0 );
    }

    /** 更新分享相关数据 */
    onUpdateShareData_blxf () {
        this._shareId = 2;
        this._isShare = !GameData_blxf.instance.onCheckShareId_blxf( this._shareId );
    }

    /** 检测是否分享 */
    onCheckIsShare_blxf () {
        return this._isShare;
    }

    /** 获取分享id */
    getShareId_blxf () {
        return this._shareId;
    }

    /** 更新摊位等级显示 */
    updateVendorLv_blxf ( isInit: boolean = false ) {
        let { vendorLv} = this._data;
        vendorLv = vendorLv || 1;

        UtilsModule_blxf.setText_blxf( this.vendorLvText, `Lv${vendorLv}`);

        isInit && this.updateSpineLv_blxf( vendorLv );

        !isInit && this.onVendorLvUpAnimation_blxf( vendorLv );
    }

    /** 检测是否可解锁 */
    onCheckIsUnlock_blxf () {
        if ( this.onCheckUnlock_blxf() ) return this.onClearUnlockAnimation_blxf();

        let { unlockType, unlockNum } = this._data;

        if ( unlockType == 9 ) return;

        let _isNum: boolean = NumModule_blxf.instance.onCheckNum_blxf( unlockType, unlockNum );
        if ( _isNum ) _isNum = this._data.onCheckIsUnlockVendor_blxf();
        if ( !_isNum ) return this.onClearUnlockAnimation_blxf();

        this.lockIconNode.active = false;
        if ( this._isLoadAnimation ) return;

        this._isLoadAnimation = true;

        let { SPINE_GAME_LOCK } = EnumManager_blxf.gameSpineType;
        UtilsModule_blxf.instance.createSpine_blxf( SPINE_GAME_LOCK, this.unlockBox, ( spineSkeleton: sp.Skeleton )=>{
            this._unlockAnimation = spineSkeleton.node;
            this._unlockAnimation.y = 8;
        });
    }

    /** 清除动画 */
    onClearUnlockAnimation_blxf () {
        if ( !this._isLoadAnimation ) return;

        this._isLoadAnimation = false;
        if ( this._unlockAnimation ) {
            this._unlockAnimation.destroy();
        }
        this._unlockAnimation = null;
        this.lockIconNode.active = true;
    }

    /** 加载商品背景 */
    loadShopBgItem ( loadNum: number ) {
        if ( loadNum >= this._totalNum ) return;

        let _options = { 
            prefabNode: this.shopItemBg,
            parentNode: this.shopItemBgBox
        };
        LoadModule_blxf.instance.LoadNode_blxf( _options );

        loadNum += 1;
        this.loadShopBgItem( loadNum );
    }

    /** 加载商品列表 */
    loadShopList_blxf () {
        let { shopList } = this._data;
        let _loadLen: number = this.shopBox.childrenCount;
        let _isLoadOk: boolean = _loadLen >= shopList.length;
        if ( _isLoadOk ) return;

        let _shopData: BaseShopData_blxf = shopList[ _loadLen ];
        this.loadShopItem_blxf( _shopData, _loadLen );

        this.onCheckAllIcon_blxf();
    }

    /** 加载商品item */
    loadShopItem_blxf ( shopData: BaseShopData_blxf, index: number ) {
        let { PREFAB_SHOP_ITEM } = EnumManager_blxf.prefabNameType;
        let _position: cc.Vec3 = this.getShopPos_blxf( index );
        let _options = {
            prefabNode : this.shopItem,
            // prefabNode : NodePool_blxf.get( PREFAB_SHOP_ITEM ),
            parentNode : this.shopBox,
            position   : _position,
            zIndex     : index,
        }
        let _shopItemNode: cc.Node = LoadModule_blxf.instance.LoadNode_blxf( _options );
        _shopItemNode.getComponent(ShopItem_blxf).initData_blxf( shopData );
    }

    /** 获取商品下标 */
    getShopPos_blxf ( index: number ) {
        let _w = 70, _h = 55;
        let _startX = -35, _startY = -27.5;
        let _spacingY = -17;

        let _xN = index % 2;
        let _yN = Math.floor( index / 2 );
        let _x = _startX + _xN * _w;
        let _y = _startY - _yN * (_h + _spacingY);
        // cc.log('_x, _y =>>', index, _x, _y);
        return cc.v3( _x, _y );
    }

    getShopNum_demo () {
        return this.shopBox.childrenCount;
    }

    /** 移除所有物品 */
    onRemoveVendorAllShop_blxf () {
        this.shopBox.destroyAllChildren();

        // this.shopBox.children.forEach( shopItem =>{
        //     this.onPut_blxf( shopItem );
        // })
        // this.shopBox.children.length = 0;
    }

    /** 检测是否解锁 */
    onCheckUnlock_blxf () {
        return this._data.onCheckUnlockVendor_blxf();
    }

    /** 检测标记 */
    onCheckIsMark_blxf () {

    }

    /** 获取摊位可操作商品id */
    onVendorShopId_blxf () {
        return this._data.onCheckShopId_blxf();
    }

    /**
     * 检测摊位
     * @param checkVendorId 摊位id 
     * @returns 
     */
    onCheckVendorId_blxf ( checkVendorId: number ) {
        let { vendorId } = this._data;

        return vendorId == checkVendorId;
    }

    /** 获取摊位id */
    getVendorId_blxf () {
        let { vendorId } = this._data;

        return vendorId;
    }

    /** 移除商品 */
    removeShop_blxf ( targetPos: cc.Vec3 = null, num: number = 0, callback: any = null, type: number = 1, isAuto: boolean = false ) {
        let _endIndex: number = this._data.shopList.length;
        let _removeShopNode: cc.Node = this.shopBox.children[ _endIndex ];
        if ( !_removeShopNode ) return;

        // 目标：摊位
        if ( !targetPos ) {
            return this.onPut_blxf( _removeShopNode );
        }

        // 目标：菜篮子
        let _canvasPos = UtilsModule_blxf.instance.getCanvasPos_blxf( _removeShopNode );

        // 更新父节点
        _removeShopNode.parent = cc.find('Canvas');
        _removeShopNode.position = _canvasPos;
        _removeShopNode.zIndex = (11 - num) * 100;

        let _isAuto = targetPos == PublicModule_blxf.diamondIconPos;

        // 飞向目标
        let { x, y } = targetPos;
        // if ( type == 1 ) num = 9 - num;
        let _t: number = type == 1 ? 0.4 : 0.2, _delayTime: number = 0.02 * num;
        if ( _isAuto ) _t = 0.7;

        // 爆竹动画
        if ( isAuto ) {
            let _shopThis: ShopItem_blxf = _removeShopNode.getComponent( ShopItem_blxf );
            // _shopThis && _shopThis.addAnimation_blxf();

            _delayTime = 0.15 * num;
            this.scheduleOnce(()=>{
                // 点火、爆竹音效
                this.onAudio_blxf( num );
                
                // 贝塞尔曲线
                this.onNodeBezier_blxf( _removeShopNode, callback );

                // 爆竹旋转
                _shopThis && _shopThis.onStartRange_blxf();
            }, _delayTime)
            return;
        }

        // 正常商品动画
        cc.tween( _removeShopNode )
        .delay( _delayTime )
        .to( _t, { x, y, scale: 0.8 }/*, cc.easeSineInOut()*/ )
        .call(()=>{
            callback && callback();
            this.onPut_blxf( _removeShopNode );
            this.updateUI_blxf();
        }).start();
    }

    onPut_blxf ( shopNode: cc.Node ) {
        shopNode.destroy();

        // let { PREFAB_SHOP_ITEM } = EnumManager_blxf.prefabNameType;
        // NodePool_blxf.put( PREFAB_SHOP_ITEM, shopNode );
    }

    onCheckAllIcon_blxf () {
        let { diamondShopId } = ConfigModule_blxf;
        let _shopNum: number = this._data.getShopNumByShopId_blxf( diamondShopId );
        let _isAll: boolean = _shopNum == this._data.maxNum;
        if ( !_isAll ) return;

        this.shopBox.children.forEach( shopItem =>{
            let _shopThis: ShopItem_blxf = shopItem.getComponent( ShopItem_blxf );
            _shopThis && _shopThis.addAnimation_blxf();
        })
    }

    /** 爆竹音效 */
    onAudio_blxf ( num: number ) {
        num % 2 == 0 && AudioModule_blxf.instance.playAudio_blxf( EnumManager_blxf.gameAudioType.AUDIO_YH_FLY );
        this.scheduleOnce(()=>{
            AudioModule_blxf.instance.playAudio_blxf( EnumManager_blxf.gameAudioType.AUDIO_YH_BOOM );
        }, 1.6);
    }

    /** 贝塞尔运动 */
    onNodeBezier_blxf ( _removeShopNode, callback ) {
        let _time: number = 1.6;
        let _x = 300 - Math.random() * 600;
        let _y = 700 - Math.random() * 700;
        let _endPos: cc.Vec3 = cc.v3(_x, _y);

        this.onBezierTo( _removeShopNode, _endPos, _time, ()=>{
            callback && callback();
            
            this.onPut_blxf( _removeShopNode );

            this.updateUI_blxf();

            this.loadBoomAnimation_blxf( _removeShopNode.parent, _endPos );
        })
    }

    /** 烟花特效 */
    loadBoomAnimation_blxf ( parentNode, endPos ) {
        let { SPINE_YH_BOOM } = EnumManager_blxf.gameSpineType;
        UtilsModule_blxf.instance.createSpine_blxf( SPINE_YH_BOOM, parentNode, ( skeleton: sp.Skeleton )=>{

        }, null, endPos);
    }

    /**
     * 贝塞尔曲线
     * @param {*} tweenNode 动画节点
     * @param {*} targetPos 终点坐标
     * @param {*} bezierTime 动画时间
     */
    onBezierTo (tweenNode, targetPos, bezierTime = 1, cb: any) {
        var _x1, _y1, _x2, _y2, _x3, _y3, _startPos, _bezier;
        _startPos = cc.v2(tweenNode.x, tweenNode.y);
        var { x: _x1, y: _y1 } = _startPos;
        var { x: _x3, y: _y3 } = targetPos;
        let _dirX: number = Math.random() > 0.5 ? 1 : -1;
        _x2 = (_x3 + _x1) * 0.5 + 500 * _dirX, _y2 = (_y3 + _y1) * 0.5;
        // cc.log('onBezierTo ==>>>', _x1, _y1, _x2, _y2, _x3, _y3);
        _bezier = [cc.v3(_x1, _y1), cc.v3(_x2, _y2), cc.v3(_x3, _y3)];
        cc.tween(tweenNode).bezierTo(bezierTime, _bezier[0], _bezier[1], _bezier[2])
        .call(()=>{
            cb && cb();
        })
        .start();
    }

    /** 商品被标记，浮起效果 */
    onMarkShopUI_blxf ( markShopIndex: number = -1, isAnimation: boolean = false ) {
        if ( markShopIndex == -1 ) {
            markShopIndex = this.shopBox.childrenCount - 1;
        }

        let _isMark: boolean = this._data.onCheckIsMark_blxf();
        let _markShopId: number = _isMark ? this._data.onCheckShopId_blxf() : -1;
        let _markShopNode = this.shopBox.children[ markShopIndex ];
        if ( !_markShopNode || !_markShopNode.parent ) return;

        let _markShopThis = _markShopNode.getComponent(ShopItem_blxf);
        let _isMarkOk: boolean = _markShopThis.onCheckMarkShop_blxf( _markShopId, isAnimation );

        // 标记中断
        if ( _markShopId != -1 && !_isMarkOk ) return;

        // 递归
        markShopIndex -= 1;
        markShopIndex >= 0 && this.onMarkShopUI_blxf( markShopIndex, isAnimation );
    }

    /** 清除延迟加载 */
    clearUpdateTimer_blxf () {
        this._updateTimer = 0;
    }

    /** 获取下一个商品终点坐标 */
    getNextShopEndPos_blxf ( addNum: number = 0 ) {
        this._updateTimer = 999;

        let _shopNum: number = this._data.getShopNum_blxf();

        // // 平移坐标
        // _shopNum += addNum;

        let _shopPos: cc.Vec3 = this.getShopPos_blxf( _shopNum );
        let _shopBoxPos: cc.Vec3 = UtilsModule_blxf.instance.getCanvasPos_blxf( this.shopBox );
        _shopBoxPos = _shopBoxPos.add( _shopPos );
        return _shopBoxPos;
    }

    /** 摊位等级动画 */
    onVendorLvTween_blxf () {
        if ( this._isLvTween ) return;

        let _isShow: boolean = this.shopBox.childrenCount == 0;
        let _isCheck = _isShow && this.vendorLvText.opacity == 100 || !_isShow && this.vendorLvText.opacity == 0;
        if ( _isCheck ) return;

        this._isLvTween = true;

        let _t: number = 0.2, _opacity: number = _isShow ? 100 : 0;
        cc.tween( this.vendorLvText ).to( _t, { opacity: _opacity }).call(()=>{
            this._isLvTween = false;
        }).start();
    }

    /** 摊位升级动画 */
    onVendorLvUpAnimation_blxf ( newLv: number ) {
        this.vendorLvUpBox.active = true;
        this.vendorLvUpBox.opacity = 255;

        let { SPINE_GAME_VENDOR_LEVELUP } = EnumManager_blxf.gameSpineType;
        UtilsModule_blxf.instance.createSpine_blxf( SPINE_GAME_VENDOR_LEVELUP, this.lvUpSpineBox, ( spineSkeleton: sp.Skeleton, duration: number )=>{
            this.scheduleOnce(()=>{
                this.vendorLvUpBox.active = false;
                this.lvUpSpineBox.destroyAllChildren();
            }, duration - 0.05);
        });

        let _delayTime1: number = 0.3, _delayTime2: number = 0.5, 
            _t1: number = 0.3, _t2: number = 0.3, 
            _opacity1: number = 0, _opacity2: number = 255;

        cc.tween( this.vendorLvUpBox )
        .delay( _delayTime1 )
        .to( _t1, { opacity: _opacity1 })
        .call(()=>{
            this.updateSpineLv_blxf( newLv );
        })
        .to( _t2, { opacity: _opacity2 })
        .delay( _delayTime2 )
        .to( _t1, { opacity: _opacity1 })
        .start();
    }

    /** 更新动画对应等级 */
    updateSpineLv_blxf ( vendorLv: number ) {
        UtilsModule_blxf.setText_blxf( this.spineLvText, `Lv${vendorLv}` );
    }

    /** 加载集满动画 */
    loadVendorAllSpine_blxf () {
        if ( this._isLoadAllAnimation ) return;
        this._isLoadAllAnimation = true;

        PageManager_blxf.instance.loadSpineVendorAll_blxf( this.allSpineBox, ( _spineSkeleton: sp.Skeleton )=>{
            if ( !_spineSkeleton ) return;
            this._allAnimation = _spineSkeleton.node;
        })
    }

    /** 清除集满动画 */
    onClearAllAnimation_blxf () {
        if ( !this._isLoadAllAnimation ) return;

        this._isLoadAllAnimation = false;
        if ( this._allAnimation ) {
            this._allAnimation.destroy();
        }
        this._allAnimation = null;
    }

}
